<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="empty===true" class="empty">
			<image style="width: 200upx;height: 200upx;" src="../../static/cart2.png" mode="aspectFit"></image>
			<view class="empty-tips" style="margin: 30upx;">
					您的购物车还是空的赶紧行动吧!
			</view>
			<view style="text-align: center; background-color: #040821;color: #fff;height: 90upx;width: 350upx;border-radius: 50upx;font-size: 38upx;line-height: 90upx;">
				<navigator url="../index/index" open-type="switchTab">去逛逛</navigator>
			</view>
		</view>
		<view>
			<!-- <view v-if="hide_list == 'none'">
				购买代理级别,先付款后提货
			</view> -->
			<!-- 列表 -->
			<!-- :style="{display:hide_list}" -->
			<view class="cart-list"  style="background-color: #ffffff;border-radius: 15upx;margin-bottom: 200upx;">
				<block v-for="(item, index) in cartList" :key="item.id">
					<view
						class="cart-item"
						:class="{'b-b': index !== cartList.length-1}"
					>
						<view class="image-wrapper" style="margin-left: 30upx;">
							<image :src="item.goods_thumb_image" 
								:class="[item.loaded]"
								mode="aspectFill" 
								lazy-load 
								@load="onImageLoad('cartList', index)" 
								@error="onImageError('cartList', index)"
								@click="jumpgoods(item.id)"
							></image>
							<view 
								class="yticon icon-xuanzhong2 checkbox"
								:class="{ checked: item.checked}"
								@click="check('item', index)"
								style="width: 0upx!important;height: 0upx!important;top: 88upx;left: -60upx;"
							></view>
						</view>
						<!-- 选择数量 -->
						<view class="item-right">
							<text class="clamp title" style="margin-top: 54upx;">{{item.goods_name}}</text>
							<text class="attr" style="height: 60upx;line-height: 60upx;">{{item.goods_short}}</text>
							
							<uni-number-box
								class="step"
								:min="0" 
								:max="999"
								:value="item.number>999?999:item.number"
								@change="numberChange($event,item)"
								style="margin-top: 10upx;"
							></uni-number-box>
						</view>
						<!-- 删除 -->
						<view @click="deleteCartItem(index)" style="flex: 0.3;">
							<view style="width: 80upx;height: 80upx;background-color: #ddddddd;text-align: center;">
								<image src="../../static/shanchu.png" style="width: 50upx;height: 50upx;top: 50upx;display: inline-block;" mode=""></image>
							</view>
							<view style="height: 80upx;line-height: 80upx;margin-top: 74upx;">¥{{item.level_price}}</view>
						</view>
					</view>
				</block>
			</view>
			<!-- 会员级别 -->
			<view style="background-color: #fff;width: 720upx;bottom: 140upx;box-shadow: 1upx 1upx 10upx #DDDDDD;border: 1upx solid #DDDDDD;border-radius: 15upx;position: fixed;z-index: 99;">
			<!-- <view style="background-color: #fff;width: 720upx;bottom: 260upx;box-shadow: 1upx 1upx 10upx #DDDDDD;border: 1upx solid #DDDDDD;border-radius: 15upx;position: fixed;z-index: 99999;"> -->
				 <!-- v-if="empty!==true" -->
				<!-- <view style="height: 60upx; margin: 15upx 50upx;font-size: 34upx;display: flex;justify-content: space-between;" @click="show_level">
					请选择级别<text class="cell-more yticon icon-you" :class="maskState===0 ? 'none' : maskState===1 ? 'show' : ''"></text>
				</view>
				<view style="margin: 15upx 10upx;border-top: 1upx solid #DDDDDD;" :style="{display: level_show}">
					<radio-group @change="radioChange" style="display: flex;justify-content: space-between;flex-direction: row;
flex-wrap: wrap;">
						<label v-for="(item, index) in arr" :key="item.value" :style="{ display: item.visibility }" style="width: 340upx;height: 70upx;">
							<view style="width: 340upx;height: 70upx;display: flex;justify-content: space-between;flex-direction: row;flex-wrap: wrap;">
								<view>
									<radio :value="item.id" :checked="item.id == current" :disabled="item.id < level_base" color="#000000" />
								</view>
								<view style="font-size: 28upx;margin-right: 10upx;">{{item.name}}</view>
								<view>
									{{item.price}}
								</view>
							</view>
						</label>
					</radio-group>
				</view> -->
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image
						:src="allChecked?'/static/selected.png':'/static/select.png'" 
						mode="aspectFit"
						@click="check('all')"
					></image>
					<!-- <view class="clear-btn" :class="{show: allChecked}" @click="clearCart">
						清空
					</view> -->
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<!-- <text class="coupon">
						已优惠
						<text>74.35</text>
						元
					</text> -->
				</view>
				<view style="width: 180upx;height: 80upx;line-height: 80upx;background-color: #000000;color: #fff;text-align: center;" @click="createOrder">
					去结算
				</view>
				<!-- <button type="primary" class="no-border confirm-btn" style="" @click="createOrder">去结算</button> -->
			</view>
			<!-- 底部白色遮挡板 -->
			<view 
				style="width: 100%;height: 250upx;background-color: #fff;z-index: 55;
				position:fixed;left: 0upx;bottom:0upx;"
			>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				user_id:'',
				res:[],
				total: 0, // 总价格
				allChecked: false, // 全选状态  true | false
				empty: false, // 空白页现实  true | false
				cartList: [],
				items: [],
				current: 0,
				level_id: 0,
				level_base: 1,
				arr:[],
				hide_list: 'block', // 跨等级购买商品隐藏购物车商品列表
				total_baseall: 0,
				level_show: 'none' ,// 显示选择及级别列表
				maskState: '',
				level_id_copy: -1,
				visibility: 'inline-block' ,// 显示隐藏,
				vipid: 0, // 个人中心页面点击进入 vip 页面传进的 vipid
			};
		},
		onLoad(e) {
			console.log(e)
			if ( e.vipid ) {
				this.vipid = e.vipid
			}
		},
		onShow(){
			// console.log(e)
			var _this = this
			uni.getStorage({
				key: 'level_id',
				success: (ress) => {
					if (_this.vipid != 0) {
						this.level_id = _this.vipid
						this.level_base = _this.vipid
						this.current = _this.vipid
					} else {
						this.level_id = ress.data
						this.level_base = this.level_id
						this.current = this.level_id // 初始化选择用户等级
					}
					
				}
			});
			uni.getStorage({
				key: 'user_id',
				success: (res) => {
					this.user_id = res.data
					uni.getStorage({
						key: 'level_id_copy',
						success: (result) => {
							_this.level_id = result.data
							console.log(_this.level_id)
							_this.loadData()
							_this.getLevel()
						},
						fail: () => {
							_this.loadData()
							_this.getLevel()
						}
					});
					
				},
				fail: () => {
					uni.navigateTo({ // 未获取到user_id
						url:'../login/login'
					})
				}
			});
		},
		
		// onPullDownRefresh() {
		// 	this.loadData()
		// 	this.getLevel()
		// 	setTimeout(function () {
		// 			uni.stopPullDownRefresh();
		// 	}, 1000);
		// },
		
		watch :{
			cartList(e,newValue,oldValue){
				//显示空白页
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		// computed:{
		// 	...mapState(['hasLogin'])
		// },
		methods: {
			loadData() {
				// this.total = 0
				var o = this
				uni.request({
				    url: 'https://cx.mingmeijt.com/Api/GoodsCart/cartList',
						method: 'POST',
						data: {
							user_id: this.user_id,
							level_id: this.level_id,
							session_id: uni.getStorageSync("sessionid")
						},
						header:{
							'Content-Type':'application/x-www-form-urlencoded',
						},
				    success: (res) => {
							if(res.data.code == 999){
								uni.navigateTo({
									url:'/pages/999/999'
								})
							};
							if(res.data.code == 998){
								uni.navigateTo({
									url:'/pages/login/login'
								})
							}
							// 每次进入购物车实时刷新用户的等级
							uni.setStorage({
								key: 'level_id',
								data: res.data.data.user_level
							})
							
							this.cartList = res.data.data.goods_cart
							if (!res.data.data.goods_cart) {
								o.cartList = []
								return
							}
							var day2 = new Date().getTime();
							for(var i=0; i<o.cartList.length; i++) {
								o.cartList[i].goods_thumb_image = 'https://cx.mingmeijt.com' + o.cartList[i].goods_thumb_image+"?time=" + day2
							}
							for(var i=0; i<o.cartList.length; i++) {
								o.cartList[i].number = parseInt(o.cartList[i].number)
							}
						}
				});
			},
			// 获取级别列表
			getLevel(){
				// 本身就是董事级别
				if ( this.level_id == 7) {
					uni.request({
						url: 'https://cx.mingmeijt.com/Api/Level/index',
						method: 'POST',
						data: {
							api_type: 'OrderStatus',
							session_id: uni.getStorageSync("sessionid"),
						},
						header:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync("sessionid")
						},
						success: (res) => {
							if(res.data.code == 999){
								uni.navigateTo({
									url:'/pages/999/999'
								})
							};
							if(res.data.code == 998){
								uni.navigateTo({
									url:'/pages/login/login'
								})
							}
							this.items = res.data.data
							var arr = [];
							for(var i = 0; i < this.items.length; i++){
								arr.push(this.items[i]);
							}
							this.arr = arr
						}
					})
				} else {
					uni.request({
						url: 'https://cx.mingmeijt.com/Api/Level/index',
						method: 'POST',
						data: {
							api_type: 'OrderStatus',
							session_id: uni.getStorageSync("sessionid")
						},
						header:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync("sessionid")
						},
						success: (res) => {
							this.items = res.data.data
							var arr = [];
							for(var i = 0; i < this.items.length; i++){
								if (this.items[i].id != 4) {
									this.items[i].visibility = 'inline-block'
								} else {
									this.items[i].visibility = 'none'
								}
								arr.push(this.items[i]);
								this.arr = arr
								if (this.items[i].id==6) {
									break;
							  }
							}
							
						}
					})
				}
			},
			// 级别列表显示隐藏
			show_level () {
				if (this.level_show == 'block') {
					this.maskState = 0;
					this.level_show = 'none' // 还原
				} else {
					this.maskState = 1;
					this.level_show = 'block' // 展开
				}
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},
			radioChange(e) {
				let arr = this.arr
				arr = arr.filter(function(item,index,array){
					return (item.id == e.detail.value);
				})
				this.level_id = e.detail.value
				this.level_id_copy = e.detail.value
				uni.setStorage({
					key: 'level_id_copy',
					data: this.level_id_copy
				})
				// if ( this.level_base < 5 && this.level_id > 4 ) {
				// 	this.total_baseall = 0
				// 	// this.total_baseall = this.total
				// 	this.hide_list = 'none'
				// 	this.total = arr[0].price
				// } else {
				// 	this.hide_list = 'block'
				// 	this.total = this.total_baseall
				// }
				this.loadData()
			},
			jumpgoods(id){
				uni.navigateTo({
					url: '/pages/product/product?goodsid=' + id
				})
			},
			 //选中状态处理
			check(type, index){
				if(type === 'item') {
					if (this.cartList[index].checked) {
						this.$set(this.cartList[index], 'checked', false)
					} else {
						this.$set(this.cartList[index], 'checked', true)
					}
					// this.cartList[index].checked = !this.cartList[index].checked;
					// console.log(this.cartList[index].checked)
				} else {
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						this.$set(item, 'checked', checked)
						// item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//数量
			numberChange(data,item){
				let index = this.cartList.indexOf(item)
				this.cartList[index].number = data
				// this.calcTotal()
				// 修改数量
				uni.request({
					url: 'https://cx.mingmeijt.com/Api/GoodsCart/updateGoodsCart',
					method: 'POST',
					data:{
						user_id: this.user_id,
						goods_id: item.id,
						number: data,
						session_id: uni.getStorageSync("sessionid"),
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded',
						'cookie': uni.getStorageSync("sessionid")
					},
					success: (res) => {
						// 这里要重新计算购物车总价
						this.calcTotal()
					}
				});
			},
			//删除
			deleteCartItem(index){
				var o = this
				let list = this.cartList;
				let row = list[index];
				var id = row.id;
				uni.request({
				    url: 'https://cx.mingmeijt.com/Api/GoodsCart/deleteGoodsCart',
						method: 'POST',
						data:{
							user_id: this.user_id,
							goods_id: id,
							session_id: uni.getStorageSync("sessionid"),
						},
						header:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync("sessionid")
						},
				    success: (res) => {
							o.cartList.splice(index, 1);
							o.calcTotal();
							uni.hideLoading();
						}
				});
				
			},
			//清空
			clearCart(){
				uni.showModal({
					content: '清空购物车？',
					success: (e)=>{
						if(e.confirm){
							this.cartList = [];
						}
					}
				})
			},
			//计算总价
			calcTotal(){
				let list = this.cartList;
				if(list.length === 0){
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item=>{
					if(item.checked === true){
						total += item.level_price * item.number;
					}else if(checked === true){
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder(){
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item=>{
					if(item.checked){
						goodsData.push({
							goodsCartId: item.id,
							number: item.number,
							goods_thumb_image: item.goods_thumb_image,
							goodsInfo_price: item.level_price,
							goods_name: item.goods_name,
							goods_desc: item.goods_desc,
						})
					}
				})
				goodsData = goodsData.filter(function(item,index,array){
					return (item.number != 0);
				})
				if (goodsData.length == 0) {
					uni.showToast({
						title: '未选择商品数量',
						icon: 'none'
					})
					return
				}
				
				uni.setStorage({
					key: 'goodsData',
					data: goodsData
				})
				// if (this.level_id_copy == -1) {
				// 	uni.showToast({
				// 		title: '请选择等级',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				// 跳转到等级购买页面
				// if ( (this.level_id == 5||this.level_id == 6) &&  this.level_base <5 ) {
				// 	uni.navigateTo({
				// 		url: '/pages/order/createOrder?level_id=' + this.level_id + '&sure=4'
				// 	})
				// }
				// else 
				if (goodsData.length != 0) {
					// 普通购物车购买
					uni.navigateTo({
						url: '/pages/order/createOrder?level_id=' + this.level_id
					})
				} else {
					uni.showToast({
						title: '未勾选商品哦!~~',
						icon: 'none'
					})
				}

			}
		}
	}
</script>

<style lang='scss'>
	page{
		background-color: #F5F5F5;
	}
	.icon-you {
		transform-origin: 5upx 20upx;
		transition: .5s;
		&.none{
			transform:rotate(0deg);
		}
		&.show{
			transform:rotate(90deg);
		}
	}
	
	.yticon,
	.icon-xuanzhong2,
	.checkbox ::before {
		content: "";
		display: block;
		width: 0px;
		height: 0px;
		background: transpant;
	}
	
	/* .cart-item .checkbox {
		margin-left: -6upx;
	} */
	
	.container{
		padding: 30upx 15upx 134upx;
		/* padding-bottom: 134upx; */
		/* 空白页 */
		.empty{
			position:fixed;
			left: 0;
			top:0;
			width: 100%;
			height: 100vh;
			padding-bottom:310upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #F5F5F5;
			image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			}
			.empty-tips{
				display:flex;
				font-size: $font-sm+2upx;
				color: $font-color-disabled;
				.navigator{
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}
	/* 购物车列表项 */
	.cart-item{
		display:flex;
		position:relative;
		padding:30upx 40upx;
		.image-wrapper{
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position:relative;
			image{
				border-radius:8upx;
			}
		}
		.checkbox{
			position:absolute;
			left:-16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 4upx;
			color: $font-color-disabled;
			background:#fff;
			border-radius: 50px;
		}
		.item-right{
			display:flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position:relative;
			padding-left: 30upx;
			.title,.price{
				font-size:$font-base + 2upx;
				color: $font-color-dark;
				height: 40upx;
				line-height: 40upx;
			}
			.attr{
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				height: 50upx;
				line-height: 50upx;
			}
			.price{
				height: 50upx;
				line-height:50upx;
			}
		}
		.del-btn{
			padding:4upx 10upx;
			font-size:34upx; 
			height: 50upx;
			color: $font-color-light;
		}
	}
	/* 底部栏 */
	.action-section{
		/* #ifdef H5 */
		margin-bottom:100upx;
		/* #endif */
		position:fixed;
		left: 15upx;
		bottom:30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 720upx;
		height: 90upx;
		padding: 0 30upx;
		background: rgba(255,255,255,.9);
		border: 1upx solid #DDDDDD;
		box-shadow: 1upx 1upx 10upx #DDDDDD;
		/* box-shadow: 0 0 5upx 0 rgba(0,0,0,.5); */
		border-radius: 16upx;
		.checkbox{
			height:52upx;
			position:relative;
			image{
				width: 52upx;
				height: 100%;
				position:relative;
				z-index: 5;
			}
		}
		.clear-btn{
			position:absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius:0 50px 50px 0;
			opacity: 0;
			transition: .2s;
			&.show{
				opacity: 1;
				width: 120upx;
			}
		}
		.total-box{
			flex: 1;
			display:flex;
			flex-direction: column;
			text-align:right;
			padding-right: 40upx;
			.price{
				font-size: $font-lg;
				color: $font-color-dark;
			}
			.coupon{
				font-size: $font-sm;
				color: $font-color-light;
				text{
					color: $font-color-dark;
				}
			}
		}
		.confirm-btn{
			padding: 0 38upx;
			margin: 0;
			/* border-radius: 100px; */
			height: 84upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
			background: #000000;
			background: linear-gradient(to right, #000000,#777777,#333333);
			box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.72)
		}
	}
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked{
		color: $uni-color-primary;
	}
</style>
